package ink.tsg.mongo.service.impl;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import ink.tsg.mongo.entity.FileEntity;
import ink.tsg.mongo.entity.User;
import ink.tsg.mongo.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {


    @Autowired
    private MongoTemplate mongoTemplate;

    // 获得SpringBoot提供的mongodb的GridFS对象
    @Autowired
    private GridFsTemplate gridFsTemplate;
    @Autowired
    private MongoDbFactory mongoDbFactory;
//    @Resource
//    private GridFSBucket gridFSBucket;

    @Override
    public void addUser(User user) {
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        User save = mongoTemplate.save(user);
        log.info("添加用户{}", save);
    }

    @Override
    public User getById(String id) {
        Query query = new Query(Criteria.where("_id").is(id));
        User one = mongoTemplate.findOne(query, User.class);
        log.info("mongo根据id{}查询结果：{}", id, one);
        return one;
    }

    @Override
    public void delById(String id) {
        User user = new User();
        user.setId(id);
        DeleteResult remove = mongoTemplate.remove(user);
        // 返回的是删除的影响条数
        long deletedCount = remove.getDeletedCount();
        log.info("mongo删除结果：{}", deletedCount);
    }

    @Override
    public void delByName(String name) {
        Query query = new Query(Criteria.where("name").is(name));
        DeleteResult remove = mongoTemplate.remove(query, User.class);
        // 返回的是删除的影响条数
        long deletedCount = remove.getDeletedCount();
        log.info("mongo删除结果：{}", deletedCount);
    }

    @Override
    public List<User> getByKeyword(String keyword) {
        Query query = new Query();
        Criteria criteria = new Criteria();
        //criteria.where("name").regex(search);
        Pattern pattern = Pattern.compile("^.*" + keyword + ".*$", Pattern.CASE_INSENSITIVE);
        Criteria.where("name").regex(pattern);
        List<User> userList = mongoTemplate.findAllAndRemove(query, User.class);
        log.info("根据名称模糊查询：{}", userList);
        return userList;
    }

    @Override
    public void updateUser(User user) {
        Query query = new Query(Criteria.where("_id").is(user.getId()));
        Update update = new Update().set("name", user.getName()).set("age", user.getAge()).set("updateTime",
                new Date());
        // updateFirst 更新查询返回结果集的第一条
        //AcknowledgedUpdateResult{matchedCount=1, modifiedCount=1, upsertedId=null}
        //UpdateResult updateResult = mongoTemplate.updateFirst(query, update, User.class);

        // updateMulti 更新查询返回结果集的全部
        // mongoTemplate.updateMulti(query,update,User.class);
        // upsert 更新对象不存在则去添加
        // AcknowledgedUpdateResult{matchedCount=0, modifiedCount=0, upsertedId=BsonString{value='222'}}
        UpdateResult updateResult = mongoTemplate.upsert(query, update, User.class);

        log.info("更新返回的结果集：{}", updateResult);
    }

    @Override
    public void saveSmallFile(MultipartFile file) throws IOException {
        FileEntity relation = new FileEntity();
//        relation.setId(UUID.randomUUID().toString());
//        relation.setContent(new Binary(file.getBytes()));
//        relation.setCreatedTime(LocalDateTime.now());
//        relation.setContentType(file.getContentType());
//        relation.setSize(file.getSize());
//        relation.setName(file.getName());
        String filename = file.getOriginalFilename();
        String type=filename.substring(filename.lastIndexOf(".")-1,filename.length());
        String s = UUID.randomUUID().toString().replaceAll("-","")+type;
        ObjectId id = gridFsTemplate.store(file.getInputStream(), s, file.getContentType());

        log.info("带文件的添加：{}",id.toString());
    }

    @Override
    public void download(String id, HttpServletResponse response) throws IOException {


        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        GridFSFile gfsfile = gridFsTemplate.findOne(query);
        String fileName = gfsfile.getFilename().replace(",", "");

        // response.setContentType(gfsfile.getContentType());

        log.info("根据id查询文件：{}",gfsfile);
        //GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //GridFsResource resource = new GridFsResource(gridFSFile, downloadStream);
        //InputStream inputStream = resource.getInputStream();
        //log.info("等到的流：{}",inputStream);

    }

    @Override
    public void delFileById(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        gridFsTemplate.delete(query);
    }


}
